package com.liaohuakai.piggybank.viewModel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.liaohuakai.piggybank.model.UserBean
import com.liaohuakai.piggybank.remote.PiggyBankServiceCreator
import com.liaohuakai.piggybank.remote.PiggyBankWebService
import com.liaohuakai.piggybank.remote.dto.UserLoginRequestDto
import com.liaohuakai.piggybank.remote.dto.UserLoginResponseDto
import com.liaohuakai.piggybank.remote.resumeWithData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * Author: Leo Liao <lliao@midtronics.com>
 * Date: 18/07/2025 15:38
 * Description:
 */
class LoginViewModel : ViewModel() {
    val isLoading = MutableLiveData<Boolean>().apply { value = false }
    val userData = MutableLiveData<UserBean>()

    suspend fun login(name: String, pw: String) {
        isLoading.value = true
        var responseDto: UserLoginResponseDto? = null
        try {
            withContext(Dispatchers.IO) {
                responseDto = PiggyBankServiceCreator.create<PiggyBankWebService>()
                    .userLogin(UserLoginRequestDto(name, pw))
                    .resumeWithData()
            }
            responseDto?.let {
                userData.value = UserBean().apply { fromLoginResponseDto(it) }
            }

        } catch (e: Exception) {
            Log.e("Leo", e.toString())
        } finally {
            isLoading.value = false
        }

    }
}